package com.vueapi.utils;

import com.vueapi.domain.HjUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtUtil {
    private static final String CLAIM_KEY_USERNAME = "sub";//用户
    private static final String SECRET = "linzhongyue";
    private static final int EXPIRE_TIME = 60 * 60 * 1000;

    /**
     * 根据用户信息生成Token
     *
     * @param hjUser hjUser
     * @return String
     */
    public static String generateToken(HjUser hjUser) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(CLAIM_KEY_USERNAME, hjUser.getUsername());

        return Jwts.builder()
                .setSubject(hjUser.getUsername())
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE_TIME))//失效时间
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();
    }

    /**
     * 从Token中获取用户名
     *
     * @param token token
     * @return String
     */
    public static String getUsernameFromToken(String token) {
        String username;
        try {
            Claims claims = getClaimsFormToken(token);
            username = claims.getSubject();//获取用户名
        } catch (Exception exception) {
            username = null;
        }
        return username;
    }

    /**
     * 根据token获取载荷（claim）  **************************
     *
     * @param token token
     * @return Claims
     */
    public static Claims getClaimsFormToken(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser().setSigningKey(SECRET)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return claims;
    }

    /**
     * 判断token是否有效
     *
     * @param token token
     * @return boolean
     */
    public static boolean validateToken(String token) {
        boolean flag = false;
        try {
            Jwts.parser().setSigningKey(SECRET).
                    parseClaimsJws(token).getBody();
            flag = true;
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return flag;
    }

    /**
     * 刷新token 就是修改创建时间
     *
     * @param token token
     * @return String
     */
    public static String refreshToken(String token) {
        Claims claims = getClaimsFormToken(token);
        return Jwts.builder()
                .setSubject(getUsernameFromToken(token))
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE_TIME))//失效时间
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();
    }

    /**
     * 判断token是否过期,失效时间时间在当前时间之前就是失效了
     *
     * @param token token
     * @return boolean
     */
    public static boolean isTokenExpired(String token) {
        Date expiredDate = getClaimsFormToken(token).getExpiration();
        return expiredDate.before(new Date());   //expiredDate < new Date()  true
    }
}
